<template>
  <div class="app-container">
    <el-card>
      <!-- 查询条件 -->
      <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="试卷名称" prop="paperName">
          <el-input
            v-model="queryParams.paperName"
            placeholder="请输入试卷名称"
            clearable
            style="width: 240px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="班级" prop="classId">
          <el-select v-model="queryParams.classId" placeholder="请选择班级" clearable style="width: 240px">
            <el-option
              v-for="dict in classOptions"
              :key="dict.classId"
              :label="dict.className"
              :value="dict.classId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="试卷状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="试卷状态" clearable>
            <el-option
              v-for="dict in paperStatusOptions"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 试卷列表 -->
      <el-table v-loading="loading" :data="paperList" style="width: 100%">
        <el-table-column label="试卷名称" align="center" prop="paperName" :show-overflow-tooltip="true" />
        <el-table-column label="班级" align="center" prop="className" />
        <el-table-column label="已批阅" align="center" width="65px">
          <template #default="scope">
            <span class="marked-count">{{ scope.row.markedCount }}</span>
          </template>
        </el-table-column>
        <el-table-column label="未批阅" align="center" width="65px">
          <template #default="scope">
            <span style="font-weight: bold" :class="{'unmarked-count': scope.row.unmarkedCount > 0}">{{ scope.row.unmarkedCount }}</span>
          </template>
        </el-table-column>
        <el-table-column label="答卷总数" align="center" width="80px">
          <template #default="scope">
            <span class="total-count">{{ scope.row.answerCount }}</span>
          </template>
        </el-table-column>
        <el-table-column label="平均分" align="center">
          <template #default="scope">
            <div class="score-display">
              <div :class="getScoreClass(scope.row.avgScore, scope.row.totalScore)">
                {{ parseFloat(scope.row.avgScore || 0).toFixed(1) }}
              </div>
              <span class="score-separator">/</span>
              <div class="total-score">
                {{ parseFloat(scope.row.totalScore || 0).toFixed(1) }}
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center">
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.status === 1">进行中</el-tag>
            <el-tag type="danger" v-else-if="scope.row.status === 2">已结束</el-tag>
            <el-tag type="warning" v-else>草稿</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="380" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button
              type="primary"
              link
              icon="View"
              @click="handleView(scope.row)"
              v-hasPermi="['manage:mark:list']"
            >查看答卷</el-button>
            <el-button
              type="danger"
              link
              icon="Refresh"
              @click="handleRemark(scope.row)"
              v-hasPermi="['manage:mark:edit']"
            >全部重批</el-button>
            <el-button
              type="success"
              link
              icon="DataAnalysis"
              @click="handleAnalysis(scope.row)"
              v-hasPermi="['manage:mark:list']"
            >试卷分析</el-button>
            <el-button
              type="warning"
              link
              icon="Download"
              @click="handleExport(scope.row)"
              v-hasPermi="['manage:mark:export']"
            >导出成绩</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>
  </div>
</template>

<script>
import { getPapersWithStats, exportGrades, remarkAll } from "@/api/manage/mark";
import { listGrade, getMyClasses } from "@/api/manage/grade";
import { getAllPaperAvgScores } from "@/api/manage/mark";
import useUserStore from '@/store/modules/user';

export default {
  name: "MarkManage",
  data() {
    return {
      // 遮罩层
      loading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 试卷列表
      paperList: [],
      // 班级选项
      classOptions: [],
      // 平均分数据
      avgScores: {},
      // 教师班级IDs
      teacherClassIds: [],
      // 是否为教师角色
      isTeacher: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        paperName: undefined,
        classId: undefined,
        status: undefined
      },
      // 试卷状态选项
      paperStatusOptions: [
        { value: "0", label: "草稿" },
        { value: "1", label: "进行中" },
        { value: "2", label: "已结束" }
      ]
    };
  },
  created() {
    this.getUserInfo();
    this.getAvgScores();
    this.getClassOptions();
  },
  activated() {
    // 当页面被激活时（例如从答卷列表页返回），重新获取数据
    this.getAvgScores();
    this.getList();
  },
  methods: {
    /** 获取用户信息和角色 */
    getUserInfo() {
      const userStore = useUserStore();
      userStore.getInfo().then(res => {
        this.isTeacher = res.roles && res.roles.includes('teacher');
        this.getList();
      }).catch(error => {
        console.error('获取用户信息失败:', error);
        this.getList();
      });
    },
    /** 获取所有试卷平均分 */
    getAvgScores() {
      return new Promise((resolve) => {
        getAllPaperAvgScores().then(response => {
          if (response.data && response.data.length > 0) {
            // 将平均分数据转换为以paperId为键的对象
            const avgScoreMap = {};
            response.data.forEach(item => {
              avgScoreMap[item.paper_id] = {
                avgScore: item.average_score,
                totalScore: item.total_score
              };
            });
            this.avgScores = avgScoreMap;
            
            // 如果已加载试卷列表，则更新平均分
            if (this.paperList.length > 0) {
              this.updatePaperAvgScores();
            }
            resolve(true);
          } else {
            resolve(false);
          }
        }).catch(error => {
          console.error('获取试卷平均分失败:', error);
          resolve(false);
        });
      });
    },
    
    /** 更新试卷列表中的平均分 */
    updatePaperAvgScores() {
      this.paperList.forEach(paper => {
        if (this.avgScores[paper.paperId]) {
          paper.avgScore = this.avgScores[paper.paperId].avgScore;
          paper.totalScore = this.avgScores[paper.paperId].totalScore;
        }
      });
    },
    
    /** 查询班级选项 */
    getClassOptions() {
      const userStore = useUserStore();
      userStore.getInfo().then(res => {
        this.isTeacher = res.roles && res.roles.includes('teacher');
        
        if (this.isTeacher) {
          // 如果是教师，只获取该教师任课的班级
          getMyClasses().then(response => {
            this.classOptions = response.data || [];
            if (this.classOptions.length > 0) {
              this.teacherClassIds = this.classOptions.map(c => c.classId);
            }
          });
        } else {
          // 如果是管理员，获取所有班级
          listGrade().then(response => {
            this.classOptions = response.rows || [];
          });
        }
      });
    },
    
    /** 查询试卷列表 */
    getList() {
      this.loading = true;
      
      // 构建查询参数
      const params = { ...this.queryParams };
      
      if (this.isTeacher && this.teacherClassIds.length > 0) {
        // 如果是教师，且指定了班级筛选条件
        if (params.classId && this.teacherClassIds.includes(parseInt(params.classId))) {
          // 使用指定的班级ID查询
        } else {
          // 使用所有任课班级查询
          params.classIds = this.teacherClassIds.join(',');
          params.classId = undefined;
        }
      }
      
      getPapersWithStats(params).then(response => {
        // 过滤结果，如果是教师只显示其任课班级的试卷
        if (this.isTeacher && this.teacherClassIds.length > 0) {
          this.paperList = response.rows.filter(paper => 
            this.teacherClassIds.includes(paper.classId) ||
            this.teacherClassIds.includes(parseInt(paper.classId))
          );
          this.total = this.paperList.length;
        } else {
          this.paperList = response.rows;
          this.total = response.total;
        }
        
        // 更新平均分信息
        this.updatePaperAvgScores();
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 查看答卷按钮操作 */
    handleView(row) {
      this.$router.push({
        name: 'MarkAnswers',
        params: { paperId: row.paperId }
      });
    },
    /** 全部重批按钮操作 */
    handleRemark(row) {
      this.$modal.confirm('确认要对试卷"' + row.paperName + '"进行全部重批操作吗？这将重新评阅所有客观题。').then(() => {
        this.loading = true;
        remarkAll(row.paperId).then(response => {
          this.$modal.msgSuccess("重批完成");
          // 使用Promise链确保先获取最新的平均分数据，再刷新试卷列表
          this.getAvgScores().then(() => {
            this.getList();
          }).finally(() => {
            this.loading = false;
          });
        }).catch(() => {
          this.loading = false;
        });
      }).catch(() => {});
    },
    /** 试卷分析按钮操作 */
    handleAnalysis(row) {
      // 检查是否有已批阅的试卷
      if (row.markedCount <= 0) {
        this.$modal.msgError("当前试卷没有已批阅的答卷，无法进行试卷分析");
        return;
      }
      
      // 跳转到试卷分析页面
      this.$router.push({
        name: 'PaperAnalysis',
        params: { paperId: row.paperId }
      });
    },
    /** 导出成绩 */
    handleExport(row) {
      const loading = this.$loading({
        lock: true,
        text: '正在导出数据，请稍候...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)',
      });
      
      exportGrades(row.paperId).then(response => {
        this.downloadExcel(response, `${row.paperName}成绩单.xlsx`);
        loading.close();
      }).catch(err => {
        loading.close();
        this.$message.error('导出失败：' + (err.message || err));
        console.error('Excel导出错误:', err);
      });
    },
    /** 下载Excel文件 */
    downloadExcel(res, fileName) {
      // 检查是否有响应
      if (!res) {
        this.$message.error('下载失败，请重试');
        console.error('下载Excel失败: 响应为空');
        return;
      }
      
      // 检查是否为错误响应
      if (typeof res === 'string' && res.includes('"code":500')) {
        try {
          const errorData = JSON.parse(res);
          this.$message.error(errorData.msg || '导出失败');
          console.error('服务器返回错误:', errorData);
        } catch (e) {
          this.$message.error('导出失败，请检查是否有数据');
          console.error('解析错误响应失败:', e, '原始数据:', res);
        }
        return;
      }
      
      try {
        // 创建Blob对象
        const blob = new Blob([res], { 
          type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
        });
        
        // 从响应头中提取文件名
        let downloadFileName = fileName;
        
        if (res.headers) {
          const contentDisposition = res.headers.get('Content-Disposition');
          if (contentDisposition) {
            // 尝试从filename*参数中提取原始文件名
            const filenameStarMatch = contentDisposition.match(/filename\*=UTF-8''([^;]+)/);
            if (filenameStarMatch && filenameStarMatch[1]) {
              downloadFileName = decodeURIComponent(filenameStarMatch[1]);
            } else {
              // 回退到普通filename参数
              const filenameMatch = contentDisposition.match(/filename="?([^";]+)"?/);
              if (filenameMatch && filenameMatch[1]) {
                downloadFileName = filenameMatch[1];
              }
            }
          }
        }
        
        // 创建下载链接
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = downloadFileName;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        URL.revokeObjectURL(link.href);
        
        // 显示成功提示
        this.$message.success('成绩单导出成功');
        console.log('Excel下载成功:', downloadFileName);
      } catch (error) {
        this.$message.error('文件下载失败: ' + error.message);
        console.error('Excel下载异常:', error);
      }
    },
    getScoreClass(avgScore, totalScore) {
      if (!avgScore || !totalScore) return 'score-fail';
      
      const percentage = (parseFloat(avgScore) / parseFloat(totalScore)) * 100;
      
      if (percentage >= 90) {
        return 'score-excellent';
      } else if (percentage >= 80) {
        return 'score-good';
      } else if (percentage >= 60) {
        return 'score-pass';
      } else {
        return 'score-fail';
      }
    }
  }
};
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.score-display {
  display: flex;
  justify-content: center;
  align-items: center;
}

.score-separator {
  margin: 0 5px;
  color: #909399;
}

.total-score {
  color: #606266;
  font-weight: bold;
}

/* 成绩样式 - 只设置文字颜色不设置背景色 */
.score-excellent {
  color: #67c23a;
  font-weight: bold;
}

.score-good {
  color: #409eff;
  font-weight: bold;
}

.score-pass {
  color: #303133;
  font-weight: bold;
}

.score-fail {
  color: #f56c6c;
  font-weight: bold;
}

/* 批阅数量样式 */
.marked-count {
  color: #409eff;
  font-weight: bold;
}

.unmarked-count {
  color: #f56c6c;
  
}

.total-count {
  color: #67c23a;
  font-weight: bold;
}
</style>
